import { Avatar, Button, Checkbox, Comment, Form, message, Modal, Popconfirm, Tooltip } from "antd";
import TextArea from "antd/lib/input/TextArea";
import moment from "moment";
import { createElement, useState } from "react";
import style from "./style.less"
import { UserInfo } from "../../interface/account";
import { IAddReply, IComment, IGoodSaveParam, IReply } from "../../interface/Article";
import { addReply, deleteHandle, setGood } from "../../service/article";
import { LikeOutlined, LikeFilled } from '@ant-design/icons';
import { getUserInfo } from "../../service/account";
import cookieStore from "../../store/cookie";
import { IReportParams } from "../../interface/reports";
import { report } from "../../service/reports";
import { myTip } from "../../tools/publicFun";

export default function Huifu(Props: { funGood: (params: IGoodSaveParam) => void, funFresh: () => void; userInfo: UserInfo, articleId: string, reply: IReply, comment: IComment }) {
  const [hasLiked, setHasLiked] = useState<boolean>(false);
  const [goodNum, setGoodNum] = useState<number>(Props.reply.like.length);
  const [modalShow, setModalShow] = useState<boolean>(false)
  const [modalType, setModalType] = useState<'report' | 'reply'>()


  async function handleDelArticle(params: IGoodSaveParam) {
    // throw new Error("Function not implemented.");
    const data = await deleteHandle(params)
    if (data.stat === 'ok') {
      Props.funFresh()
      message.success('删除成功')
    } else {
      message.error(data.msg)
    }
  }
  const actions = [
    <Tooltip key="comment-basic-like" title="Like">
      <span onClick={() => handleGood({ type: 'reply', userId: Props.userInfo.id, commentId: Props.comment.id, replyId: Props.reply.id, articleId: Props.articleId })}>
        {createElement(hasLiked ? LikeFilled : LikeOutlined)}
        <span className="comment-action">{goodNum}</span>
      </span>
    </Tooltip>,
    <span key="comment-basic-reply-to" onClick={() => { setModalShow(true); setModalType('reply') }}>回复</span>,
    <span key="comment-basic-report" onClick={() => { setModalShow(true); setModalType('report') }}>举报</span>,
    <Popconfirm
      title="确定删除该评论?"
      onConfirm={() => handleDelArticle({ type: 'reply', userId: Props.userInfo.id, articleId: Props.articleId, commentId: Props.comment.id, replyId: Props.reply.id })}
      okText="Yes"
      cancelText="No"
    ><span key="comment-basic-delete">删除</span></Popconfirm>,
  ];

  async function handleGood(params: IGoodSaveParam) {
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      const data = await setGood(params)
      if (data.stat === 'ok') {
        setHasLiked(!hasLiked)
        if (hasLiked) {
          setGoodNum(goodNum - 1)
        } else {
          setGoodNum(goodNum + 1)
        }
        // window.location.reload()
      } else {
        message.warn("参数错误")
      }
    } else {
      alert("检测到未登录，请登录")
      // setShowLoginModal(true)
    }
  }

  async function handleAddReply(value: { content: string }) {
    // throw new Error("Function not implemented.");
    const Params: IAddReply = {
      authorId: Props.userInfo.id,
      content: value.content,
      targetUserId: Props.comment.author.id,
      commentId: Props.comment.id,
      articleId: Props.articleId
    }
    const data = await addReply(Params)
    if (data.stat === 'ok') {
      message.success("评论成功")
      setModalShow(false)
      Props.funFresh()
    }
  }

  async function handleReport(value: { content: string, type: string[] }) {
    // throw new Error("Function not implemented.");
    const requestParams: IReportParams = { ...value, targetType: 'comment', replyId: Props.reply.id, articleId: Props.articleId, commentId: Props.comment.id, userId: Props.userInfo.id }
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      const data = await report(requestParams)
      if (data.stat === 'ok') {
        myTip("举报成功", 'success')
        setModalShow(false)
      } else {
        myTip(data.msg, 'fail')
      }
    } else {
      alert("检测到未登录，请登录")
      setModalShow(true)
    }
  }

  return (
    <div>
      <Comment
        actions={actions}
        author={<a href={window.location.host + "/#/userInfo/userId=" + Props.reply.author?.id!}>{Props.reply.author?.nickname!}</a>}
        avatar={<Avatar src={Props.reply.author?.avatar!} alt="Han Solo" />}
        content={
          <p>
            {"回复：" + Props.reply.targetUser?.nickname! + "：" + Props.reply.content}
          </p>
        }
        datetime={
          <Tooltip title={moment().format('YYYY-MM-DD HH:mm:ss')}>
            <span>{moment(Number(Props.reply.create_Ts)).format('YYYY-MM-DD HH:mm:ss')}</span>
          </Tooltip>
        }
      />
      <div className={style.divider}>
      </div>
      <div>
        <Modal destroyOnClose footer={null} onCancel={() => { setModalShow(false) }} visible={modalShow} >
          {modalType === 'report' ? (<Form className={style.reportForm} onFinish={(value: { content: string, type: string[] }) => { handleReport(value) }}>
            <Form.Item label={"请填写举报原因"} name={"content"}>
              <TextArea maxLength={200} />
            </Form.Item>
            <Form.Item label={"请选择其中一到三项"} name={"type"}>
              <Checkbox.Group>
                <Checkbox value={"1"}>含有色情内容</Checkbox>
                <Checkbox value={"2"}>涉及第三方资金相关内容</Checkbox>
                <Checkbox value={"3"}>含有不良政治言论</Checkbox>
                <Checkbox value={"4"}>其他违规内容</Checkbox>
              </Checkbox.Group>
            </Form.Item>
            <Form.Item>
              <Button htmlType={"submit"} type={"primary"}>举报</Button>
            </Form.Item>
          </Form>) : (
            <Form onFinish={(value) => { handleAddReply(value) }}>
              <Form.Item label={""} name={"content"}>
                <TextArea placeholder={"回复：" + Props.reply.author?.nickname!} />
              </Form.Item>
              <Form.Item>
                <Button htmlType={"submit"} type={"primary"}>评论</Button>
              </Form.Item>
            </Form>
          )}
        </Modal>
      </div>
    </div>
  );
}